package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.RedisConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.behavior.pojos.Behavior;
import com.heima.model.behavior.vo.BehaviorVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {



    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;



    /**
     * 保存app端相关的文章数据
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveAppArticle(ArticleDto dto) {

       /* try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        //1.校验参数
        if(dto == null ){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //属性拷贝
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);

        //2.判断是否存在id
        if(dto.getId()  == null){
            //2.1 不存在id  新增  ap_article,ap_article_config,ap_article_content
            save(apArticle);

            //保存配置   都给默认值
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //保存内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        }else {
            //2.2 存在id   修改  ap_article,ap_article_content
            updateById(apArticle);

            //修改内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        //生成文章详情页面



        //3.数据返回  article的id
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 用户行为数据回显
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
//        构建参数
        BehaviorVo data=new BehaviorVo();
        data.check();

//        获取用户id
        Integer id = AppThreadLocalUtil.getUser().getId();
        String userid=id.toString();
//        从缓存中获取数据
        Object isfollow = redisTemplate.opsForHash().get
                (RedisConstants.USER_ID_ + userid, RedisConstants.AUTHOR_ID_ + dto.getAuthorId());
        if (isfollow!=null){
            data.setIsfollow(true);
        }
         String mapJSON =(String) redisTemplate.opsForValue().get(userid);
        Map map = JSON.parseObject(mapJSON, Map.class);

        if (map==null ){
            return ResponseResult.okResult(data);
        }

        String behaviorString =(String) map.get(dto.getArticleId());
        if (behaviorString==null){
            return ResponseResult.okResult(data);
        }
        Behavior behavior = JSON.parseObject(behaviorString, Behavior.class);

        Boolean islike = behavior.getIslike();
        Boolean isunlike = behavior.getIsunlike();
        Boolean iscollection = behavior.getIscollection();
        if (iscollection){
            data.setIscollection(iscollection);
        }
        if (isunlike){
            data.setIsunlike(isunlike);
        }

        if (islike){
            data.setIslike(islike);
        }


        return ResponseResult.okResult(data);
    }

    @Autowired
    private ApArticleMapper apArticleMapper;

    private static final Short MAX_PAGE_SIZE = 50;

    /**
     * 查询文章列表
     * @param dto
     * @param type
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, Short type) {

        //校验参数
        //分页校验
        Integer size = dto.getSize();
        if(size == null || size == 0){
            size = 10;
        }
        size = Math.min(size,MAX_PAGE_SIZE);
        dto.setSize(size);

        //校验tag
        if(StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间校验
        if(dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if(dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());

        //加载文章
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, type);
        return ResponseResult.okResult(articleList);
    }
}
